package com.wuhao.code.check.model

import com.aegis.mybatis.xmlless.annotations.JoinObject
import com.aegis.mybatis.xmlless.enums.JoinType
import com.aegis.mybatis.xmlless.model.ObjectJoinInfo
import com.aegis.mybatis.xmlless.model.Properties
import com.aegis.mybatis.xmlless.model.TypeInfo
import com.aegis.mybatis.xmlless.model.base.BaseJoinObjectProvider
import com.aegis.mybatis.xmlless.util.TableInfoProvider
import com.wuhao.code.check.getStringAnnoValue
import net.sf.jsqlparser.parser.CCJSqlParserUtil
import net.sf.jsqlparser.schema.Column
import org.jetbrains.kotlin.psi.KtDeclaration

/**
 *
 * @author 吴昊
 * @date 2024/1/23 16:50
 * @since v0.0.0
 * @version 1.0
 */
class KtElementJoinObjectProvider(
    private val ktProperty: KtDeclaration,
    private val genericType: TypeInfo,
    private val selectedProperties: List<String>,
    private val property: String
) : BaseJoinObjectProvider {

  override fun resolve(): ObjectJoinInfo {
    val xmllessTableInfo = TableInfoProvider.getOrInitXmllessTableInfo(genericType.realType)
    val joinOnTargetProperty =
        (ktProperty.getStringAnnoValue(JoinObject::class.java, JoinObject::joinOnTargetProperty) ?: "").ifBlank {
          xmllessTableInfo.keyProperty ?: error("持久化对象${genericType.realType.getClassName()}缺少主键字段")
        }
    val joinOnThisProperty =
        ktProperty.getStringAnnoValue(JoinObject::class.java, JoinObject::joinOnThisProperty) ?: ""
    val targetTableName = resolveJoinTableName(joinOnThisProperty, this.getAlias(), xmllessTableInfo)
    return ObjectJoinInfo(
        genericType.realType.getClassName(),
        xmllessTableInfo,
        Properties(selectedProperties),
        targetTableName,
        JoinType.valueOf(
            ktProperty.getStringAnnoValue(
                JoinObject::class.java,
                JoinObject::joinType
            ) ?: "LEFT"
        ),
        Column(joinOnThisProperty),
        CCJSqlParserUtil.parseExpression(joinOnTargetProperty),
        associationPrefix = property + "_",
        javaType = genericType
    )
  }

  override fun getAlias(): String {
    return ktProperty.getStringAnnoValue(
        JoinObject::class.java, JoinObject::alias
    ) ?: ""
  }

}
